package cn.template.serve_project.config.shiro.realm;


import cn.template.serve_project.config.shiro.JwtToken;
import cn.template.serve_project.constant.JwtConstant;
import cn.template.serve_project.enums.R;
import cn.template.serve_project.exception.BusinessException;
import cn.template.serve_project.util.HttpUtil;
import cn.template.serve_project.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Map;

@Slf4j
public class JwtRealm extends AuthorizingRealm {
    /*
     * 多重写一个support
     * 标识这个Realm是专门用来验证JwtToken
     * 不负责验证其他的token（UsernamePasswordToken）
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    //这个token就是从过滤器中传入的jwtToken
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwt = (String) token.getPrincipal();
        if (jwt == null) {
            throw new BusinessException(R.ERROR_LOGIN_NOT);
        }
        //判断
        if (!JwtUtil.isVerify(jwt)) {
            throw new UnknownAccountException();
        }
        Map<String, Object> stringObjectMap = JwtUtil.parseToken(jwt);
        //这里返回的是类似账号密码的东西，但是jwtToken都是jwt字符串。还需要一个该Realm的类名
        return new SimpleAuthenticationInfo(jwt, jwt, "JwtRealm");

    }

}